import { sys } from "cc";

/**
 * @name 本地储存工具
 * @author qianShang
 * @version 20230831
 */
export default class StorageUtil {
    private static _Ins: StorageUtil;
    public static get Ins() {
        if (this._Ins == null) {
            this._Ins = new StorageUtil();
        }
        return this._Ins;
    }

    /**
     * 保存数据到本地
     * @param key 键
     * @param value 值
     */
    public set(key: string, value: any) {
        if (typeof value === 'object') {
            sys.localStorage.setItem(key, JSON.stringify(value));
        } else {
            sys.localStorage.setItem(key, value);
        }
    }

    /**
     * 读取本地数据
     * @param key 键
     * @param parse 解析
     */
    public get(key: string, parse: boolean = true) {
        const dataString = sys.localStorage.getItem(key);
        if (dataString) {
            if (parse) {
                try {
                    return JSON.parse(dataString);
                } catch {
                    return dataString;
                }
            }
            return dataString;
        }
        return null;
    }

    /**
     * 移除本地数据
     * @param key 键
     */
    public remove(key: string) {
        sys.localStorage.removeItem(key);
    }

}
